angular.module('message-list', ['swipe-list'])

.controller 'MessageListCtrl', ($scope, $state, $http, $ionicHistory, $stateParams, newAddress, wfCache,showToast,$ionicViewSwitcher,userData,$ionicPopup,paginationFactory) ->
    paginationSrv = new paginationFactory('MessageListCtrl','/systemmsg/')
    _.extend $scope,
        canLoadMore: -> paginationSrv.canLoadMore()
        doRefresh: ->
            paginationSrv.reload(true).finally -> $scope.$broadcast 'scroll.refreshComplete'
        loadMore: ->
            paginationSrv.loadMore().finally -> $scope.$broadcast 'scroll.infiniteScrollComplete'
        goBack: ->
            $ionicViewSwitcher.nextDirection('back')
            $ionicHistory.goBack()
        pick: (i) ->
            console.log 'pick',i
            $http.post("/systemmsg/",{action:'setstatus',userid:userData.getToken(),id:$scope.messageList[i].id})
            .success (resp)->
                if resp?.status=='0'
                    paginationSrv.reload(true, {
                        action:'msglist'
                        userid: userData.getToken()
                    })
                    alertPopup = $ionicPopup.alert {title:'信息', template:$scope.messageList[i].txt2}
                else
                    showToast resp.msg
            .error ->
                showToast '网络错误'


        remove: (i) ->
            $http.post("/systemmsg/",{action:'delmsg',userid:userData.getToken(),id:$scope.messageList[i].id})
            .success (resp)->
                if resp?.status=='0'
                    $scope.messageList.splice(i,1)
                else
                    showToast '删除失败'
            .error ->
                showToast '网络异常'

    unWatch = paginationSrv.watch (data) ->
        $scope.messageList = []
        _.each data,(item)->
            if item.isread=='0'
                isread = '(未读)'
            else
                isread = '(已读)'
            $scope.messageList.push {id:item.id,txt1:"#{item.title}#{isread}",txt2:item.content,txt3:item.addtime}
    paginationSrv.reload(true, {
        action:'msglist'
        userid: userData.getToken()
    })
    $scope.$on '$destory', ->
        unWatch()
